package com.zzl.car.handle;

import com.zzl.car.context.ZdpJwtUserContext;
import com.zzl.car.exception.ZdpException;
import com.zzl.car.util.ZdpJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* 拦截器，用于处理JWT验证
* */
public class ZdpJwtHandler implements HandlerInterceptor {
    /*
    * 对于登录请求，放行
    * 对于其他请求，需要请求头部中带有 Authorization 参数
    * 字段的内容为后端生成返回给前端的token
    * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("==========");
        System.out.println(requestURI);
        //如果是登录请求，就放行
        /*
        * 登录放行
        * */
        if(requestURI.equals("/login")
                ||requestURI.equals("/verify")
                ||requestURI.equals("/managerLogin")
                ||requestURI.equals("/register")
                ||requestURI.equals("/payDemo")
                ||requestURI.equals("/notifyurl")
                ||requestURI.equals("/returnurl")
                ||requestURI.equals("/hello")
                ){
            System.out.println("------------======");
            return true;
        }
        System.out.println(request.getHeader("Authorization"));
        String authorization = request.getHeader("Authorization");
        Claims claim = ZdpJwtUtil.parse(authorization);
        //如果已经登录，放行
        if(claim!=null){
            ZdpJwtUserContext.add(claim.getSubject());
            return true;
        }
        //如果没有登录，就抛出异常
        response.setHeader("Access-Control-Allow-Origin","* ");
        response.setStatus(200);
        throw new ZdpException(1001,"请先登录");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ZdpJwtUserContext.remove();
    }
}
